import java.util.HashMap;

class Solution {
    public int totalFruit(int[] fruits) {
        HashMap<Integer,Integer> map = new HashMap<>();
        int left = 0;
        int right = 0;
        int maxLen = 0;
        for (; right < fruits.length; right++) {
            if (map.containsKey(fruits[right])) {//
                map.put(fruits[right],map.get(fruits[right])+1);
            }else {
                map.put(fruits[right],1);
            }
            if (map.size() > 2) {
                while (map.get(fruits[left]) != 0) {
                    map.put(fruits[left],map.get(fruits[left])-1);
                    if (map.get(fruits[left]) == 0) {
                        map.remove(fruits[left]);
                        left++;
                        break;
                    }
                    left++;
                }
            }
            maxLen = Math.max(maxLen,right-left+1);
        }
        return maxLen;
    }
}